package com.imay.live.activity.discovery;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.live.R;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.RoomLiveShortActivity;
import com.imay.live.activity.RoomPushShortActivity;
import com.imay.live.adapter.DiscoveryIndicatorAdapter;
import com.imay.live.adapter.SupperTypeAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.model.ShortLiveInfoModel;
import com.imay.live.model.SupperModel;
import com.imay.live.model.TopicModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.indicator.Indicator;
import com.imay.live.view.indicator.ScrollIndicatorView;
import com.imay.live.view.indicator.slidebar.ColorBar;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.viewtype.SupperModelType;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by lzx on 2017/07/25 0025.
 */

public class SupperDekaronActivity extends BaseRequestActivity {
    private static final String MODEL = "topicModel";
    private TopicModel topicModel;
    private ArrayList<MultiItemEntity> mdatas;
    private View titleLayout;
    private RecyclerView mrecyclerView;
    private SupperTypeAdapter mAdapter;
    private ArrayList<MultiItemEntity> mrecomdatas;
    private ArrayList<MultiItemEntity> mnewdatas;
    private TwinklingRefreshLayout mRefreshLayout;
    private int COUNT = 21;
    private View noMoreView;
    private View noDataView;
    private int choosetype = 0;
    private boolean leftmore = false;
    private boolean rightmore = false;
    ScrollIndicatorView indicatorView;
    int currentselect = 0;

    public static void start(Context context, TopicModel topicModel) {
        Intent intent = new Intent(context, SupperDekaronActivity.class);
        intent.putExtra(MODEL, topicModel);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.supperdekaron_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        topicModel = getIntent().getParcelableExtra(MODEL);
        if (topicModel == null || topicModel.getId() < 0) {
            finish();
            return;
        }
        setTitle("#" + topicModel.getTitle());
        mrecyclerView = $(R.id.trl_recyclervew);
        mRefreshLayout = $(R.id.trl_refresh);
        titleLayout = LayoutInflater.from(this).inflate(R.layout.suppernewtitle_layout, mRefreshLayout, false);
        final View view_top = titleLayout.findViewById(R.id.view_top);
        TextView tv_content = (TextView) titleLayout.findViewById(R.id.tv_content);
        TextView tv_auther = (TextView) titleLayout.findViewById(R.id.tv_auther);
        SpannableString spanstring = new SpannableString(getResources().getString(R.string.str_textfrom, topicModel.getAuthorName()));
        spanstring.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_70)), 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv_auther.setText(spanstring);
        tv_content.setText(topicModel.getContent());
        final ScrollIndicatorView mIndicatorView = (ScrollIndicatorView) LayoutInflater.from(this).inflate(R.layout.supperdekaron_title, mRefreshLayout, false);
        indicatorView = $(R.id.title_layout);
        initIndicatorView(mIndicatorView);
        initIndicatorView(indicatorView);
        indicatorView.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {
                mIndicatorView.setCurrentItem(select);
                selectTab(select);
            }
        });
        mIndicatorView.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {
                indicatorView.setCurrentItem(select);
                selectTab(select);
            }
        });
        mdatas = new ArrayList<MultiItemEntity>();
        mAdapter = new SupperTypeAdapter(mdatas);
        mrecomdatas = new ArrayList<MultiItemEntity>();
        GridLayoutManager layoutManager
                = new GridLayoutManager(this, 3);
        mrecyclerView.setLayoutManager(layoutManager);
        mrecyclerView.setHasFixedSize(true);
        mrecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .size((int) getResources().getDimension(R.dimen.size_10dp)).color(Color.WHITE)
                .build());
        mrecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.dekoron_fl) {
                    Object o = adapter.getItem(position);
                    if (o instanceof SupperModelType) {
                        List supperModelTypes = adapter.getData().subList(0, position);
                        List<Long> infoModels = new ArrayList<Long>();
                        for (Object object : supperModelTypes) {
                            if (object instanceof SupperModelType) {
                                SupperModelType supperModelType = (SupperModelType) object;
                                infoModels.add(supperModelType.getShortLiveInfoModel().getShortLiveId());
                            }
                        }
                        SupperModelType supperModelType = (SupperModelType) o;
                        infoModels.add(supperModelType.getShortLiveInfoModel().getShortLiveId());
                        RoomLiveShortActivity.startActivity(SupperDekaronActivity.this, infoModels, supperModelType.getShortLiveInfoModel().getChallengeId(), supperModelType.getType());
                    }
                }

            }
        });
        mAdapter.bindToRecyclerView(mrecyclerView);


        noMoreView = LayoutInflater.from(this).inflate(R.layout.no_more_layout, mRefreshLayout, false);
        noDataView = LayoutInflater.from(this).inflate(R.layout.load_layout, mRefreshLayout, false);
        ImageView progress = (ImageView) noDataView.findViewById(R.id.progress_icon);
        TextView load_text = (TextView) noDataView.findViewById(R.id.load_text);
        load_text.setText(getResources().getString(R.string.str_nomore));
        load_text.setVisibility(View.VISIBLE);
        progress.clearAnimation();
        progress.setImageResource(R.mipmap.wushuju);
        mRefreshLayout.setOnScrollListener(new TwinklingRefreshLayout.OnScrollListener() {
            @Override
            public void onScrolled() {
                float outh = mIndicatorView.getY();
                float y = mAdapter.getHeaderLayout().getY() + mrecyclerView.getY();
                float top = y + outh;
                if (top >= 0) {
                    float f = 1 - top / (outh);
                    if (f <= 1) {
                        view_top.setAlpha(f);
                    }
                }
                if (top <= 0) {
                    indicatorView.setVisibility(View.VISIBLE);
                } else {
                    indicatorView.setVisibility(View.GONE);
                }
            }
        });
        mAdapter.addHeaderView(titleLayout);
        mAdapter.addHeaderView(mIndicatorView);
        indicatorView.setVisibility(View.INVISIBLE);
        RefreshView headerView = new RefreshView(this);
        LoadingView bottomProgressView = new LoadingView(this);
        mRefreshLayout.setHeaderView(headerView);
        mRefreshLayout.setBottomView(bottomProgressView);
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setEnableOverScroll(false);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadmoredata(mdatas.size(), COUNT, topicModel.getId(), choosetype);
            }
        });
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setChildView(mrecyclerView);
        mAdapter.addFooterView(noDataView);
        loaddata(0, COUNT, topicModel.getId(), choosetype);
        TextView btn_start = (TextView) titleLayout.findViewById(R.id.btn_start);
        if (topicModel.getMedal() == 1) {
            btn_start.setVisibility(View.VISIBLE);
            btn_start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RoomPushShortActivity.startActivity(SupperDekaronActivity.this, topicModel.getId());
                    MobclickAgent.onEvent(SupperDekaronActivity.this, "jiuwan_click");

                }
            });
        } else {
            btn_start.setVisibility(View.GONE);
        }

        MobclickAgent.onEvent(this, "title_open");

    }

    private void selectTab(int select) {
        if (currentselect == select) {
            return;
        }
        currentselect = select;
        if (select == 0) {
            choosetype = 0;
            if (mnewdatas != null) {
                mnewdatas.clear();
                mnewdatas.addAll(mdatas);
            }
            mdatas.clear();
            mdatas.addAll(mrecomdatas);
            if (mdatas.size() == 0) {
                if (noMoreView.getParent() != null) {
                    mAdapter.removeFooterView(noMoreView);
                }
                if (noDataView.getParent() == null) {
                    mAdapter.addFooterView(noDataView);
                }
            } else {
                if (noDataView.getParent() != null) {
                    mAdapter.removeFooterView(noDataView);
                }
                if (leftmore) {
                    if (noMoreView.getParent() != null) {
                        mAdapter.removeFooterView(noMoreView);
                    }
                } else {
                    if (noMoreView.getParent() == null)
                        mAdapter.addFooterView(noMoreView);
                }
            }
            mRefreshLayout.setEnableLoadmore(leftmore);
            mAdapter.notifyDataSetChanged();
            if (indicatorView.getVisibility() == View.VISIBLE) {
                mrecyclerView.scrollToPosition(mAdapter.getHeaderLayoutCount());
                mrecyclerView.scrollBy(0, -indicatorView.getMeasuredHeight());
            }
        } else {
            choosetype = 1;
            mrecomdatas.clear();
            mrecomdatas.addAll(mdatas);
            if (mnewdatas == null) {
                mnewdatas = new ArrayList<MultiItemEntity>();
                if (noMoreView.getParent() != null) {
                    mAdapter.removeFooterView(noMoreView);
                }
                if (noDataView.getParent() == null) {
                    mAdapter.addFooterView(noDataView);
                }
                mdatas.clear();
                mAdapter.notifyDataSetChanged();
                loaddata(0, COUNT, topicModel.getId(), choosetype);
            } else {
                mdatas.clear();
                mdatas.addAll(mnewdatas);
                if (mdatas.size() == 0) {
                    if (noMoreView.getParent() != null) {
                        mAdapter.removeFooterView(noMoreView);
                    }
                    if (noDataView.getParent() == null) {
                        mAdapter.addFooterView(noDataView);
                    }
                } else {
                    if (noDataView.getParent() != null) {
                        mAdapter.removeFooterView(noDataView);
                    }
                    if (rightmore) {
                        if (noMoreView.getParent() != null) {
                            mAdapter.removeFooterView(noMoreView);
                        }
                    } else {
                        if (noMoreView.getParent() == null)
                            mAdapter.addFooterView(noMoreView);
                    }
                }
                mRefreshLayout.setEnableLoadmore(rightmore);
                mAdapter.notifyDataSetChanged();
                if (indicatorView.getVisibility() == View.VISIBLE) {
                    mrecyclerView.scrollToPosition(mAdapter.getHeaderLayoutCount());
                    mrecyclerView.scrollBy(0, -indicatorView.getMeasuredHeight());
                }
            }
        }
    }

    void initIndicatorView(ScrollIndicatorView mIndicatorView) {
        String[] tabTitles = new String[]{getString(R.string.str_recommend), getString(R.string.str_newdata)};
        ColorBar colorBar = new ColorBar(SupperDekaronActivity.this, getResources().getColor(R.color.text_8d), (int) getResources().getDimension(R.dimen.size_3dp));
        colorBar.setWidth((int) getResources().getDimension(R.dimen.tab_ind_w));
        mIndicatorView.setScrollBar(colorBar);
        DiscoveryIndicatorAdapter mIndicatorAdapter = new DiscoveryIndicatorAdapter(SupperDekaronActivity.this, getSupportFragmentManager(), tabTitles, R.layout.view_indicator_search);
        mIndicatorView.setAdapter(mIndicatorAdapter.getIndicatorAdapter());
    }

    private void loaddata(int start, int count, int challengeId, final int type) {//0 -1
        ProtoRequestHelper.task(ProtoHttpFactory.getShortLiveDetail(start, count, challengeId, type)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<SupperModel> result = JSON.parseObject(data, new TypeReference<Result<SupperModel>>() {
                    }.getType());
                    int count = 0;
                    if (result.result == CodeSuccess && result.data != null && result.data.getShortLiveInfos() != null) {
                        count = result.data.getShortLiveInfos().size();
                        mdatas.clear();
                        for (int i = 0; i < count; i = i + 1) {
                            SupperModelType supperModelType = new SupperModelType();
                            ShortLiveInfoModel shortLiveInfoModel = result.data.getShortLiveInfos().get(i);
                            shortLiveInfoModel.setExample(false);
                            if (result.data.getTopic() != null && result.data.getTopic().getExampleId() != 0) {
                                if (result.data.getTopic().getExampleId() == shortLiveInfoModel.getShortLiveId()) {
                                    shortLiveInfoModel.setExample(true);
                                } else {
                                    if (i < 4 && type == 0) {
                                        SpannableString spanstring = new SpannableString(getResources().getString(R.string.str_textNO, i));
                                        spanstring.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bg_c8)), 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                        supperModelType.setNumber(spanstring);
                                    }
                                }
                            } else {
                                if (i < 3 && type == 0) {
                                    SpannableString spanstring = new SpannableString(getResources().getString(R.string.str_textNO, i + 1));
                                    spanstring.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bg_c8)), 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                    supperModelType.setNumber(spanstring);
                                }
                            }
                            supperModelType.setType(type);
                            supperModelType.setShortLiveInfoModel(shortLiveInfoModel);
                            mdatas.add(supperModelType);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                    boolean ismore = count >= COUNT;
                    mRefreshLayout.setEnableLoadmore(ismore);
                    if (type == 0) {
                        leftmore = ismore;
                    } else {
                        rightmore = ismore;
                    }
                    if (mdatas.size() == 0) {
                        if (noDataView.getParent() == null) {
                            mAdapter.addFooterView(noDataView);
                        }
                    } else {
                        if (noDataView.getParent() != null) {
                            mAdapter.removeFooterView(noDataView);
                        }
                        if (ismore) {
                            if (noMoreView.getParent() != null) {
                                mAdapter.removeFooterView(noMoreView);
                            }
                        } else {
                            if (noMoreView.getParent() == null) {
                                mAdapter.addFooterView(noMoreView);
                            }
                        }
                    }
                } catch (Exception e) {
                    if (noDataView.getParent() == null) {
                        mAdapter.addFooterView(noDataView);
                    }
                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                if (noDataView.getParent() == null) {
                    mAdapter.addFooterView(noDataView);
                }

            }
        });
    }

    private void loadmoredata(int start, int count, int challengeId, final int type) {//0 -1
        ProtoRequestHelper.task(ProtoHttpFactory.getShortLiveDetail(start, count, challengeId, type)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    int count = 0;
                    Result<SupperModel> result = JSON.parseObject(data, new TypeReference<Result<SupperModel>>() {
                    }.getType());
                    if (result.result == CodeSuccess && result.data != null && result.data.getShortLiveInfos() != null) {
                        count = result.data.getShortLiveInfos().size();
                        for (int i = 0; i < count; i = i + 1) {
                            SupperModelType supperModelType = new SupperModelType();
                            ShortLiveInfoModel shortLiveInfoModel = result.data.getShortLiveInfos().get(i);
                            supperModelType.setShortLiveInfoModel(shortLiveInfoModel);
                            supperModelType.setType(type);
                            mdatas.add(supperModelType);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                    boolean ismore = count >= COUNT;
                    if (type == 0) {
                        leftmore = ismore;
                    } else {
                        rightmore = ismore;
                    }
                    mRefreshLayout.setEnableLoadmore(ismore);
                    if (!ismore) {
                        if (noMoreView.getParent() == null)
                            mAdapter.addFooterView(noMoreView);
                    } else {
                        if (noMoreView.getParent() != null)
                            mAdapter.removeFooterView(noMoreView);
                    }
                    mRefreshLayout.finishLoadmore();
                } catch (Exception e) {
                    mRefreshLayout.finishLoadmore();
                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                mRefreshLayout.finishLoadmore();
            }
        });
    }
}
